package com.sina.weibo.sdk.demo;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.widget.Toast;

import com.sina.weibo.sdk.auth.Oauth2AccessToken;
import com.sina.weibo.sdk.exception.WeiboException;
import com.sina.weibo.sdk.net.RequestListener;
import com.sina.weibo.sdk.openapi.StatusesAPI;
import com.sina.weibo.sdk.openapi.models.ErrorInfo;
import com.sina.weibo.sdk.openapi.models.Status;
import com.sina.weibo.sdk.openapi.models.StatusList;

public class SendWeibo {

	/** 当前 Token 信息 */
	private static Oauth2AccessToken mAccessToken;
	/** 用于获取微博信息流等操作的API */
	private static StatusesAPI mStatusesAPI;

	private static Context context;

	public SendWeibo(Context context) {
		this.context = context;
		init();
	}

	private static void init() {
		// 获取当前已保存过的 Token
		mAccessToken = AccessTokenKeeper.readAccessToken(context);
		// 对statusAPI实例化
		mStatusesAPI = new StatusesAPI(context, Constants.APP_KEY, mAccessToken);
	}

	public void sendSimpleText(String str) {
		mStatusesAPI.update(str, null, null, mListener);
	}

	public void sendPicText(String str) {
		Drawable drawable = context.getResources().getDrawable(R.drawable.ic_com_sina_weibo_sdk_logo);
		Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
		mStatusesAPI.upload("str", bitmap, null, null, mListener);
	}

	private static RequestListener mListener = new RequestListener() {
		@Override
		public void onComplete(String response) {
			if (!TextUtils.isEmpty(response)) {
				if (response.startsWith("{\"statuses\"")) {
					// 调用 StatusList#parse 解析字符串成微博列表对象
					StatusList statuses = StatusList.parse(response);
					if (statuses != null && statuses.total_number > 0) {
						Toast.makeText(context, "获取微博信息流成功, 条数: " + statuses.statusList.size(), Toast.LENGTH_LONG)
								.show();
					}
				} else if (response.startsWith("{\"created_at\"")) {
					// 调用 Status#parse 解析字符串成微博对象
					Status status = Status.parse(response);
					Toast.makeText(context, "发送一送微博成功, id = " + status.id, Toast.LENGTH_LONG).show();
				} else {
					Toast.makeText(context, response, Toast.LENGTH_LONG).show();
				}
			}
		}

		@Override
		public void onWeiboException(WeiboException e) {
			ErrorInfo info = ErrorInfo.parse(e.getMessage());
			Toast.makeText(context, info.toString(), Toast.LENGTH_LONG).show();
		}
	};

}
